import axios from "axios";
import * as Cookies from 'js-cookie';
import store from '~/store';

const requestInterceptor = config => {
  // content type
  config.headers["Content-Type"] = "application/json";
  // csrf token
  const csrfToken = Cookies.get('csrfToken');
  if (csrfToken) {
    newOptions.headers['X-Csrf-Token'] = csrfToken;
  }
  // access token
  // const accessToken = store.state.accessToken;
  // if (accessToken) {
  //   newOptions.headers['Access-Token'] = `Bearer ${accessToken}`;
  // }
  // Access-Token
  config.headers["Access-Token"] =
    "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MzMyODUzMjIsImV4cCI6MTUzMzM3MTcyMn0.KzNT9UdQFjzWXBWiJZnQFTD4GUyiSGe5ET6Mr9AucEc";
  return config;
};

const http = axios.create({
  baseURL: "http://127.0.0.1:7001",
  timeout: 30000
});

// cors cookie
axios.defaults.withCredentials = true;

// interceptors
http.interceptors.request.use(requestInterceptor);
http.interceptors.response.use(
  response => {
    const accessToken = response.headers['access-token'];
    if (accessToken) {
      store.dispatch('saveToken', accessToken)
    }
    return response.data;
  },
  error => {
    console.log("err" + error);
    return Promise.reject(error);
  }
);

export const download = axios.create({
  baseURL: "http://127.0.0.1:7001",
  responseType: "blob"
});

download.interceptors.request.use(requestInterceptor);

export default http;
